var express = require("express");
var router = express.Router();

// 引入lowdb持久化数据
const shortid = require("shortid");
const low = require("lowdb");
const FileSync = require("lowdb/adapters/FileSync");
const adapter = new FileSync(__dirname + "/../data/db.json");
const db = low(adapter);

router.get("/account", function (req, res, next) {
  const accounts = db.get("accounts").value();
  res.render("list", { accounts });
});

router.get("/account/create", function (req, res, next) {
  res.render("create");
});

router.post("/account", function (req, res, next) {
  let id = shortid.generate();
  db.get("accounts")
    .unshift({ id: id, ...req.body })
    .write();

  res.render("success", { msg: "添加成功哦~~~~", url: "/account" });
});

router.get("/account/:id", function (req, res, next) {
  const id = req.params.id;
  db.get("accounts").remove({ id }).write();

  res.render("success", { msg: "删除成功哦~~~~", url: "/account" });
});

module.exports = router;
